define([
  'EventBus',
  ELMP.resource('index.js', 'workflow_sdk')
], function (EventBus, WorkflowSdk) {
  'use strict'
  function calcKey (key) {
    return `__workflow__${key}`
  }
  const methods = {
    getBaseInfo: calcKey('getBaseInfo'),
    initEventBus: calcKey('initEventBus'),
    getInitData: calcKey('getInitData'),
    beforeSubmit: calcKey('beforeSubmit'),
    processGetValue: calcKey('processGetValue'),
    processSetValue: calcKey('processSetValue')
  }
  return {
    data () {
      return {
        baseInfoRef: 'baseInfo',
        businessObjectRef: 'businessObject',
        reviewObjectRef: 'reviewObject',
        currentNodeProcessInfo: null,
        activityId: '', // 节点id
        nextActivityId: '', // 下一个节点
        businessKey: '',
        nodeVfun: [],
        reviewItemList: []
      }
    },
    created () {
      this[methods.initEventBus]()
    },
    computed: {
      processInfo () {
        return WorkflowSdk.useCache().get('processInfo')
      },
      // 流程链表
      flowLink () {
        const activities = this.processInfo.activities ?? []
        const startNode = activities.find(node => node.properties.type === 'startEvent')
        const endNode = activities.find(node => node.properties.type === 'endEvent')
        const nodeList = activities.filter(node => node.properties.type === 'userTask' && node.properties.serialnumber)
        nodeList.sort((before, after) => parseInt(before.properties.serialnumber) - parseInt(after.properties.serialnumber))
        nodeList.unshift(startNode)
        nodeList.push(endNode)
        return $.flow.createFlowMap(nodeList.map(node => node.activityId))
      },
      // 当前流程
      currentFlow () {
        return this.flowLink.searchData(this.activityId)
      },
      // 是否最后节点
      isTail () {
        return this.flowLink.getTail().data === this.activityId
      },
      // 当前节点索引
      activityIdIndex () {
        return this.flowLink.indexOf(this.activityId)
      },
      // 是否是当前审批人
      taskDisabled () {
        return !this.currentNodeProcessInfo?.taskId
      }
    },
    methods: {
      async [methods.getBaseInfo] () {
        let baseInfo = {}
        // 从流程按钮点进来 获取不到提交信息
        if (this.$refs[this.baseInfoRef]) {
          baseInfo = await this.$refs[this.baseInfoRef].getFormData() // 获取基本信息
        }
        return baseInfo
      },
      // 注册事件
      [methods.initEventBus] () {
        EventBus.once('process:customForm:setValue', this[methods.processSetValue])
        EventBus.once('process:customForm:getValue', this[methods.processGetValue])
        EventBus.once('workflow:machining:before:submit', this[methods.beforeSubmit])
      },
      // 获取初始化信息
      async [methods.getInitData] (data) {
        let reviewItemList = []
        let roleDtoList = []
        if (this.$refs[this.businessObjectRef]) {
          reviewItemList = this.$refs[this.businessObjectRef].getTableData().map(c => ({ oid: c.id }))
        } else if (this.$refs[this.reviewObjectRef]) {
          reviewItemList = this.$refs[this.reviewObjectRef].getTableData()
        } else {
          reviewItemList = this.reviewItemList
        }
        if (this.$refs.memberList) {
          roleDtoList = await this.$refs.memberList.getTableData(false, this.nodeVfun)
        }
        // 获取流程下一个节点
        let sessionId = ''
        const reqData = {
          processInstanceId: this.currentNodeProcessInfo.processInstanceId,
          routeFlag: data.fp_route_flag,
          activityId: this.activityId
        }
        const resp = await $.elApi.flow.fetchProcessNextTask(reqData)
        if (resp.code === '200') {
          sessionId = resp.res.data.length > 0 ? resp.res.data[0].nextKey : ''
        }
        const baseInfo = await this[methods.getBaseInfo]()
        // 上下文
        const containerOid = baseInfo?.containerOid ? baseInfo?.containerOid : ''
        const formJsonStr = {
          roleDtoList,
          reviewItemList,
          containerOid
        }
        const _userMap = {}
        const _roleMap = {}
        Object.keys(data).forEach(c => {
          if (c.indexOf('_assignee') !== -1 && c.length > 9) {
            _userMap[c] = data[c]
          }
          if (c.indexOf('_role') !== -1 && c.length > 5) {
            _roleMap[c] = data[c]
          }
        })
        const parmar = {
          baseForm: {
            processBasicInfo: baseInfo,
            businessForm: { reviewItemList },
            businessFormJsonStr: JSON.stringify(formJsonStr)
          },
          baseSubmitTaskDto: {
            routeFlag: data.fp_route_flag,
            sessionId,
            taskId: this.currentNodeProcessInfo.taskId,
            comment: data.comment,
            dueDate: data.dueDate,
            priority: data.priority,
            userMap: _userMap,
            roleMap: _roleMap,
            uploadFileIds: data.uploadFileIds

          },
          pboId: this.currentNodeProcessInfo.businessKey,
          processInstanceId: this.currentNodeProcessInfo.processInstanceId
        }
        return parmar
      },
      // 提交之前
      async [methods.beforeSubmit] (evt, data) {
        if (data?.baseForm) {
          const baseInfo = await this[methods.getBaseInfo]()
          data.baseForm.processBasicInfo = Object.assign(data.baseForm.processBasicInfo, baseInfo)
        } else {
          data = await this[methods.getInitData](data)
        }
        data.processDefinitionId = this.currentNodeProcessInfo.processDefinitionId
        this.submit(data)
      },
      [methods.processGetValue] (evt, callback) {
        callback()
      },
      [methods.processSetValue] (evt, data) {
        const that = this
        this.currentNodeProcessInfo = data
        this.activityId = data.activityId

        $.el.post({
          url: ELMP.postUrl('workflow/v1/findformdata/bypobandnodekey'),
          data: {
            pboId: data.businessKey,
            sessionId: data.activityId,
            processDefinitionId: data?.processDefinitionId || '',
            taskId: data?.taskId || '',
            executionId: data?.id || ''
          },
          success (res) {
            that.getdata(Object.assign(res.data, { activityId: data.activityId }))
          },
          error (err) {
            $.msg.error(err.message)
          }
        })
      },
      // 获取数据
      handleCloseClick () {
        $.form.backSidepage()
      },
      getdata (data) {
        console.log(data)
      },
      submit (data) {
        console.log(data)
      }
    }
  }
})
